package com.tedu.egmvcboot.controller;

import com.tedu.egmvcboot.mapper.UserMapper;
import com.tedu.egmvcboot.pojo.dto.UserArticleDTO;
import com.tedu.egmvcboot.pojo.dto.UserLoginDTO;
import com.tedu.egmvcboot.pojo.entity.Article;
import com.tedu.egmvcboot.pojo.vo.UserVO;
import com.tedu.egmvcboot.result.JsonResult;
import com.tedu.egmvcboot.result.Status;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/v1/users")
@Slf4j
@Api(tags = "用户模块")
@Validated
public class UserController {
    @Autowired
    private UserMapper userMapper;
    @ApiOperation(value = "用户登录")
    @PostMapping("/login")
    public JsonResult login(@RequestBody @Validated UserLoginDTO userLoginDTO, @ApiIgnore HttpSession session){
        UserVO userVO = userMapper.selectUser(userLoginDTO.getUsername(),userLoginDTO.getPassword());
        log.warn("用户名:{}",userLoginDTO.getUsername());
        if(userVO != null) {
            log.warn("用户名:{}",userVO.getUsername());
            session.setAttribute("user",userVO);
            return new JsonResult(Status.OPERATION_SUCCESS);
        }
        return new JsonResult(Status.USERNAME_PASSWORD_ERROR);
    }

    @PostMapping("/article")
    @ApiOperation("发表文章功能")
    public JsonResult insertArticle(@RequestBody @Validated UserArticleDTO userArticleDTO, @ApiIgnore HttpSession session){
        UserVO userVO = (UserVO)session.getAttribute("user");

        Article article = new Article();
        BeanUtils.copyProperties(userArticleDTO,article);
        article.setUserId(userVO.getId());
        userMapper.insertArticle(article);
        return new JsonResult(Status.OPERATION_SUCCESS);
    }
    @ApiOperation("查询指定文章")
    @GetMapping("/selectByArticleId")
    public JsonResult findArticleById(@Range(min = 1,max = 100,message = "文章ID必须在1-100之间") @RequestParam Integer id){
        return new JsonResult(Status.OPERATION_SUCCESS,userMapper.selectByArticleId(id));
    }
}
